// 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.formatStr = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

var PN = location.pathname.split(/\//)[1];
var webPath = '/' + PN + '/';
var webStaticPath = webPath + 'static/';
var baseServices_restfulUrl = webPath;

function getLoginData () {
    $.ajax({
        type: "get",
        async: false,
        url: baseServices_restfulUrl + "admin/adminuser/getCurrentUser.json",
        success: function (data, textStatus) {
            if (data.state == 0) {
                setSessionJson('curUserObj', data.data);
            } else {
                console.log(data);//--> Object {code: 1, total: 0}
                console.log("您还没有登录 或 太久没操作，服务器断开，请重新登录！");
                location.href = webStaticPath + "login.html";
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("服务器异常或重启了，请重新登录后再试 ！");
            location.href = webStaticPath + "login.html";
        }
    });

}

// getSessionData();


//根据key截取获取数组
function splitParam (obj, key) {
    var o = [];
    if (obj == null || obj == undefined || obj == "") {
        return "";
    }
    return o = obj.split(key);
}

function getRouteUrl () {
    var groupMap = new Object();
    //各组二级菜单
    var group1 = ["console"];
    var group2 = ["fishpondstageList", "workingCalendar", "wordingLogMain", "fishorigin"];
    var group3 = ["corpEdit", "pondList", "fishTypeList", "fishpondstageEdit", "techList", "preventList", "baitList"];
    var group4 = ["userList", "treePage", "appVersionList"];
    var group5 = ["machinesList"];

    for (var i = 0; i < group1.length; i++) {
        groupMap[group1[i]] = "group1";
    }
    for (var i = 0; i < group2.length; i++) {
        groupMap[group2[i]] = "group2";
    }
    for (var i = 0; i < group3.length; i++) {
        groupMap[group3[i]] = "group3";
    }
    for (var i = 0; i < group4.length; i++) {
        groupMap[group4[i]] = "group4";
    }
    for (var i = 0; i < group5.length; i++) {
        groupMap[group5[i]] = "group5";
    }

    var ret = new Object();
    var url = window.location.href;
    if (url.indexOf("#/") != -1) {
        var str = url.split("#/");
        str = str[1];
        if (str.indexOf("/") != -1) {
            strs = str.split("/");
            if (strs[0].indexOf("Edit") != -1) {
                strs[0] = strs[0].replace(/Edit/g, "List");
            }
            for (var i = 0; i < strs.length; i++) {
                ret["leve" + i] = strs[i];
            }
        } else {
            if (str.indexOf("Edit") != -1) {
                str = str.replace(/Edit/g, "List");
            }
            ret["leve0"] = str;
        }
        ret["group"] = groupMap[ret["leve0"]];
        return ret;
    } else {
        return "";
    }
}
function GetRequest () {
    var url = window.location.href;
    //var theRequest = new Object();
    if (url.indexOf("#/") != -1) {
        var str = url.split("#/");
        str = str[1];
        if (str.indexOf("/") != -1) {
            strs = str.split("/");
        } else {
            strs = str;
        }
        /*for(var i = 0; i < strs.length; i ++) {
         theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
         }*/
        //console.log("strs:"+strs);
    }
    //return theRequest;
}
function getYestoday (date) {
    var yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
    var yesterday = new Date();
    yesterday.setTime(yesterday_milliseconds);

    var strYear = yesterday.getFullYear();
    var strDay = yesterday.getDate();
    var strMonth = yesterday.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    datastr = strYear + "-" + strMonth + "-" + strDay;
    return datastr;
}

//获得上个月在昨天这一天的日期
function getLastMonthYestdy (date) {
    var daysInMonth = new Array([0], [31], [28], [31], [30], [31], [30], [31], [31], [30], [31], [30], [31]);
    var strYear = date.getFullYear();
    var strDay = date.getDate();
    var strMonth = date.getMonth() + 1;
    if (strYear % 4 == 0 && strYear % 100 != 0) {
        daysInMonth[2] = 29;
    }
    if (strMonth - 1 == 0) {
        strYear -= 1;
        strMonth = 12;
    }
    else {
        strMonth -= 1;
    }
    strDay = daysInMonth[strMonth] >= strDay ? strDay : daysInMonth[strMonth];
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    datastr = strYear + "-" + strMonth + "-" + strDay;
    return datastr;
}

//获得上一年在昨天这一天的日期
function getLastYearYestdy (date) {
    var strYear = date.getFullYear() - 1;
    var strDay = date.getDate();
    var strMonth = date.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    datastr = strYear + "-" + strMonth + "-" + strDay;
    return datastr;
}

function getObjWidthHeight (id) {
    var ret = new Object()
    var obj = document.getElementById(id);
    ret["width"] = obj.offsetWidth;
    ret["height"] = obj.offsetHeight;
    return ret;
}


/**
 * 类似java的方式拷贝（克隆）对象 ，仅把目标对象已存在的属性从原对象中获取
 * @param src
 * @param dest
 * @returns {Clone}
 */
function copyObjectSameJava (src, dest) {
    var obj = cloneObject(src);
    for (var a in obj) {
        if (dest.hasOwnProperty(a)) {
            dest[a] = obj[a];
        }
    }

}

/**
 * 克隆 js 对象 ，标准js赋值是通过 地址传递的
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
function cloneObject (obj) {
    function Clone () {
    }

    Clone.prototype = obj;
    var o = new Clone();
    for (var a in o) {
        if (typeof o[a] == "object") {
            o[a] = cloneObject(o[a]);
        }
    }
    return o;
}

function getSessionJson (key) {
    isEmpty(sessionStorage.getItem(key)) ? sessionStorage.setItem(key, JSON.stringify({})) : '';
    return JSON.parse(sessionStorage.getItem(key));
}
function setSessionJson (key, json) {
    sessionStorage.setItem(key, JSON.stringify(json));
    return sessionStorage.getItem(key);
}
function removeSession (key) {
    if (!isEmpty(key)) sessionStorage.removeItem(key);
}

/**
 数组移除 null 元素
 */
Array.prototype.removeNullObj = function () {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == null) {
            this.splice(i, 1);
            i--;
        }
    }
};
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};
String.prototype.ltrim = function () {
    return this.replace(/(^\s*)/g, "");
};
String.prototype.rtrim = function () {
    return this.replace(/(\s*$)/g, "");
};

/**
 * [判空]
 * @author liuxiaotang
 * @param  {String |Object |Array |Number}  para [null]
 * @return {Boolean}      [true | false]
 */
function isEmpty (para) {
    if (typeof(para) === "undefined") {
        return true;
    } else if (typeof(para) === "string") {
        return (para === '');
    } else if (para instanceof Array) {
        return (para.length === 0);
    } else if (typeof(para) === "object" && !(para instanceof Array)) {
        var para_name;
        for (para_name in para) {
            return false;
        }
        return true;
    } else if (typeof(para) === "number") {
        isEmpty(para + '');
    }
}

/**
 * [onlyNum input输入框只能输数字]
 * @author liuxiaotang
 * @param  {Object} event [NOT NULL，不传会导致不兼容firefox和ie]
 * @param  {Number} length [小数点位数，为空时默认没有小数]
 * @return {Boolean}       [description]
 *
 *  example:
 *  <input type="text" onkeydown="return onlyNum(event,2);" onkeyup="this.value=this.value.replace(/[\u4e00-\u9fa5]|[(~！@#￥%…&*（）—=·+{}：“《》？、。，‘’；】【\-)+]/g,'')"
 onpaste="return false" ondrop="return false" required>
 *
 *  onkeydown不加return会导致不兼容firefox/ie
 *
 */
function onlyNum (event, length) {
    var input = event.target.value;
    var point = (length === undefined || /\./.exec(input)) ? 0 : 1;

    var e = (event) ? event : ((window.event) ? window.event : "");//兼容IE和Firefox获得keyBoardEvent对象
    var key = e.keyCode ? e.keyCode : e.which;//兼容IE和Firefox获得keyBoardEvent对象的键值

    if (e.shiftKey) { //shift + any key
        e.returnValue = false;
        return false;
    }

    if ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || (point && (key == 190 || key == 110))) { // 数字键
    } else if (key == 8 || key == 9 || key == 13 || (key >= 37 && key <= 40 || key == 46)) {//功能键
    } else {
        e.returnValue = false;
        return false;
    }

    if (input.indexOf('.') != -1) {
        var decimal = input.substring(input.indexOf('.') + 1);
        if (decimal.length >= length) {
            if (key == 8 || key == 9 || key == 13 || (key >= 37 && key <= 40 || key == 46)) {//功能键
            } else {
                e.returnValue = false;
                return false;
            }
        }
    }
}

/**
 * 检查手机号是否正确
 * @param phone
 * @returns {boolean}
 */
function checkPhone (phone) {
    return /^1(3|4|5|7|8|9)\d{9}$/.test(phone);
}

/**
 * 移除数组中匹配的元素
 *
 * a=['001','002','003'];
 * a.removeArrItem['002'];//==>['001','003'];
 *
 * @param item
 */
Array.prototype.removeItem = function (item) {
    var idx = this.indexOf(item);
    idx != -1 ? this.splice(idx, 1) : console.log('数组[' + this + ']中没有匹配"' + item + '"的参数');
};

/**
 * 数组去重
 */
Array.prototype.removeIdentical = function () {
    var tempArr = [];
    for (var v in this) {
        if (this.hasOwnProperty(v)) {
            if (!tempArr[this[v]]) {
                tempArr[this[v]] = this[v];
            } else {
                this.splice(v, 1);
            }
        }
    }
};

/*cookies*/
function getCookie (c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            c_end == -1 ? c_end = document.cookie.length : '';
            return decodeURI(document.cookie.substring(c_start, c_end));
        }
    }
    return ""
}
function setCookie (c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + encodeURI(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
function removeCookie (name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

/**
 * json格式的string字符串格式化输出
 * @param {String} txt
 * @param {Boolean} compress 是否为压缩模式
 * @returns {string|Boolean}
 */
function beautyJsonStr (txt, compress) {
    var indentChar = '    ';
    if (/^\s*$/.test(txt)) {
        alert('数据为空,无法格式化! ');
        return false;
    }
    try {
        var data = eval('(' + txt + ')');
    }
    catch (e) {
        alert('数据源语法错误,格式化失败! 错误信息: ' + e.description, 'err');
        return false;
    }
    var draw = [], last = false, This = this, line = compress ? '' : '\n', nodeCount = 0, maxDepth = 0;

    var notify = function (name, value, isLast, indent/*缩进*/, formObj) {
        nodeCount++;
        /*节点计数*/
        for (var i = 0, tab = ''; i < indent; i++)tab += indentChar;
        /* 缩进HTML */
        tab = compress ? '' : tab;
        /*压缩模式忽略缩进*/
        maxDepth = ++indent;
        /*缩进递增并记录*/
        if (value && value.constructor == Array) {/*处理数组*/
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + '[' + line);
            /*缩进'[' 然后换行*/
            for (var i = 0; i < value.length; i++)
                notify(i, value[i], i == value.length - 1, indent, false);
            draw.push(tab + ']' + (isLast ? line : (',' + line)));
            /*缩进']'换行,若非尾元素则添加逗号*/
        } else if (value && typeof value == 'object') {/*处理对象*/
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + '{' + line);
            /*缩进'{' 然后换行*/
            var len = 0, i = 0;
            for (var key in value)len++;
            for (var key in value)notify(key, value[key], ++i == len, indent, true);
            draw.push(tab + '}' + (isLast ? line : (',' + line)));
            /*缩进'}'换行,若非尾元素则添加逗号*/
        } else {
            if (typeof value == 'string') value = '"' + value + '"';
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + value + (isLast ? '' : ',') + line);
        }
    };
    var isLast = true, indent = 0;
    notify('', data, isLast, indent, false);
    return draw.join('');
}

/**
 * 解析如url的查询字符串为 js对象
 * @param {String} queryString example：closeSocket=fromUser&arg2=off&arg3=1
 * @returns {Object}
 */
function parseQueryStringToObj (queryString) {
    var argArray = queryString.replace("?", "").split("&");
    var argObj = {};
    for (var i = 0; i < argArray.length; i++) {
        if (argArray[i].indexOf("=") !== -1) {
            var tempArray = argArray[i].split("=");
            argObj[tempArray[0]] = tempArray[1];
        }
    }
    return argObj;
}
//==================== Array 扩展=======================
/**
 * array 序号
 * @param obj
 * @param compareFunc [可选] 对比function
 *      function(a,b)
 * @returns {number}
 */
Array.prototype.indexOf = function (obj, compareFunc) {

    if (!compareFunc) {//如果对比function为null就创建一个
        compareFunc = function (a, b) {
            return a == b;
        }
    }

    var size = this.length;
    for (var i = 0; i < size; i++) {
        if (compareFunc(obj, this[i])) {
            return i;
        }
    }
    return -1;
}

/**
 * 删除元素
 * @param obj
 * @param compareFunc [可选] 对比function
 *      function(a,b)
 */
Array.prototype.removeItem = function (obj, compareFunc) {
    var index = this.indexOf(obj, compareFunc);
    if (index != -1) {
        this.splice(index, 1);
    }
}

/**
 *交换元素
 * @param $a 子元素a 序列
 * @param $b 子元素b 序列
 */
Array.prototype.swap = function ($a, $b) {
    if ($a == $b) {
        return;
    }
    var $tmp = this[$a];
    this[$a] = this[$b];
    this[$b] = $tmp;
}

/**
 * 移动元素，并交换位置
 * @param child 数组子元素
 * @param offset 偏移值
 */
Array.prototype.swapOffset = function (child, offset) {
    var orgin = this.indexOf(child);
    var target = orgin + offset;
    target = Math.max(0, Math.min(target, this.length - 1));
    this.swap(orgin, target);
}

//==================== String 扩展=======================
/**
 * 是否以 prefix 开头
 * @param prefix
 * @returns {boolean}
 */
String.prototype.startsWith = function (prefix) {
    return this.slice(0, prefix.length) === prefix;
}

/**
 * 是否以 suffix 结尾
 * @param suffix
 * @returns {boolean}
 */
String.prototype.endsWith = function (suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};